<?php

class User extends CActiveRecord
{
	/**
	 * The followings are the available columns in table 'yii_users':
	 * @var integer $id
	 * @var string $contract
	 * @var string $account
	 * @var string $ip_address
	 * @var string $username
	 * @var string $balance
	 * @var string $abonplata
	 * @var string $limit
	 * @var string $end_time
	 * @var string $pkt_end_time
	 * @var integer $packet_id
	 * @var integer $speed_id
	 * @var integer $blocked
	 * @var integer $blocked_by_bill
	 * @var integer $enabled
	 * @var string $address
	 * @var string $email
	 * @var string $telephon
	 * @var integer $active
	 * @var string $change_time
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{users}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('contract, account, ip_address', 'required'),
			array('packet_id, speed_id', 'numerical', 'integerOnly'=>true),
			//array('end_time', 'type', 'type'=>'datetime'), 
			array('balance, abonplata', 'numerical'),
			array('blocked, enabled', 'boolean'),
			array('email', 'email'),
			//array('ip_address', 'match', 'pattern'=>'\d+'),
			array('contract, account', 'length', 'max'=>10),
			array('ip_address', 'application.extensions.IPValidator'),
			array('username, address, email, telephon', 'length', 'max'=>50),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'packet'=>array(self::BELONGS_TO,'Packet','packet_id',
						'select'=>'id,name',
						),
			'speed'=>array(self::BELONGS_TO,'Speed','speed_id',
						'select'=>'id,name',),
			'payment'=>array(self::HAS_MANY,'Payment','user_id',
						//'select'=>'',
						//'order'=>'payment_date DESC', //TODO Не используеться в АктивДатаПровайдере ;(
						//'condition'=>'active=1',
						)
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => Yii::t('user', 'Id'),
			'contract' => Yii::t('user', 'Contract'),
			'account' => Yii::t('user', 'Account'),
			'ip_address' => Yii::t('user', 'IP Address'),
			'username' => Yii::t('user', 'User Name'),
			'balance' => Yii::t('user', 'Balance'),
			'abonplata' => Yii::t('user', 'Abonplata'),
			'limit' => Yii::t('user', 'Limit'),
			'end_time' => Yii::t('user', 'End Time'),
			'pkt_end_time' => Yii::t('user', 'Packet End Time'),
			'packet_id' => Yii::t('user', 'Packet'),
			'speed_id' => Yii::t('user', 'Speed'),
			'blocked' => Yii::t('user', 'Blocked By Admin'),
			'blocked_by_bill' => Yii::t('user', 'Blocked By System'),
			'enabled' => Yii::t('user', 'Is Enable'),
			'address' => Yii::t('user', 'Address'),
			'email' => Yii::t('user', 'Email'),
			'telephon' => Yii::t('user', 'Telephon'),
			'active' => Yii::t('user', 'Is Active'),
			'change_time' => Yii::t('user', 'Change Time'),
		);
	}
	
	//Корректировка отображения даты
	public function behaviors()
	{
		return array('datetimeI18NBehavior' => array('class' => 'ext.DateTimeI18NBehavior')); // 'ext' is in Yii 1.0.8 version. For early versions, use 'application.extensions' instead.
	}
	
	public function initialDataFilter()
	{
		$filters = new CDataFilter($this,'f');
		$filters->addFilter(new CFilterSearch('s'), Yii::t('user', 'Search'));
		
		$filters->addFilter(new CFilterDropdown('p',array(
				'emptyValue'=>Yii::t('user', 'All'),
				'specialOptions'=>array('null'=>Yii::t('user', 'None')),
				'displayName'=>Yii::t('user', 'Packet'),
			)),Yii::t('user', 'Filter'));
		
        $filters->addFilter(new CFilterDropdown('b',array(
        		'displayName'=>Yii::t('user', 'Blocked By System')
        	)),Yii::t('user', 'Filter'));
        
        $filters->addFilter(new CFilterLink('a', Yii::t('user', 'All users'), '1', true), Yii::t('user', 'Show'));
        $filters->addFilter(new CFilterLink('a', Yii::t('user', 'Deleted users'), '0'), Yii::t('user', 'Show'));
		
        return $filters;
	}
	// Returns list of searchable fileds for DataFilter widget
	public function getDataFilterSearchFields($filterName)
    {
        switch ($filterName) {
            case 's': //filter name
                return array(
                    't.contract'=>Yii::t('user', 'Contract'), //field name => display name
                    't.account'=>Yii::t('user', 'Account'),
                    't.ip_address'=>Yii::t('user', 'IP Address'),
                	't.username'=>Yii::t('user', 'User Name'),
                );
        }
    }

    // Returns options for DataFilter widget
    public function getDataFilterOptions($filterName)
    {
        switch ($filterName) {
           case 'p':  //filter name
                // data from database
                return CHtml::listData(Packet::model()->active()->findAll(array()), 'id', 'name');
           case 'b':
                // static data (not from database)
                $options = array(
                    array('id'=>'', 'name'=>Yii::t('user', 'All')),
                    array('id'=>1, 'name'=>Yii::t('user', 'Blocked')),
                    array('id'=>0, 'name'=>Yii::t('user', 'Not blocked')),
                );
                return CHtml::listData($options, 'id', 'name');
        }      
    }
	
    // Applies search criteria enterd using DataFilter widget
    public function applyDataSearchCriteria(&$criteria, $filterName, $searchField, $searchValue)
    {
        if($filterName == 's') {
            $localCriteria = new CDbCriteria;
            //$localCriteria->condition = ' '.$searchField.' LIKE "%'.$searchValue.'%" ';
            $localCriteria->condition = ' '.$searchField.' LIKE :searchValue ';
            $localCriteria->params = array(':searchValue'=>'%'.$searchValue.'%');
            $criteria->mergeWith($localCriteria);
        }
    }
    
    // Applies filter criteria enterd using DataFilter widget
    public function applyDataFilterCriteria(&$criteria, $filterName, $filterValue)
    {	
        if($filterName == 'p') {
            $localCriteria = new CDbCriteria;
            if ($filterValue != 'null') {
            	CDataFilter::setCondition('packet_id', $filterValue, $localCriteria);
            } else {
            	//$localCriteria->with(array('packet'=>array('condition'=>'packet.active=0')));
            	$localCriteria->condition = 'packet.active=0';
            }
            $criteria->mergeWith($localCriteria);
        }

        if($filterName == 'a') {
            if ($filterValue == 'not_active') {
            	$criteria->addCondition('t.active=0','OR');
            }
        }

        if($filterName == 'b') {            
            $localCriteria = new CDbCriteria;
            CDataFilter::setCondition('blocked_by_bill', $filterValue, $localCriteria);
            $criteria->mergeWith($localCriteria);
        }
    }
    
}